package middleware

import (
	"github.com/beego/beego/v2/server/web/context"
	"order/global"
	"order/pkg"
	"time"
)

func OrderAuth(c *context.Context) {
	token := c.Request.Header.Get("token")
	if token == "" {
		jsonR := global.JsonR{
			Code: -1,
			Msg:  "token为空",
			Data: nil,
		}
		c.JSONResp(jsonR)
		return
	}
	payload, f, err := pkg.GetJwtTokenPayload(token)
	if err != nil {
		jsonR := global.JsonR{
			Code: -1,
			Msg:  "token解析失败",
			Data: nil,
		}
		c.JSONResp(jsonR)
		return
	}
	timer := time.Unix(int64(f), 0)
	//判断过期时间是否超过当前时间
	if time.Now().After(timer) {
		jsonR := global.JsonR{
			Code: -1,
			Msg:  "token已过期",
			Data: nil,
		}
		c.JSONResp(jsonR)
		return
	}

	//存储token
	c.Input.SetData("userId", payload)
}
